package com.doone.telmarket.action.admin;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.doone.telmarket.domain.Currency;
import com.doone.telmarket.domain.ServiceOrder;
import com.doone.telmarket.domain.ServiceOrderMode;
import com.doone.telmarket.domain.ServicePage;
import com.doone.telmarket.domain.ServicePageContent;
import com.doone.telmarket.domain.ServiceProduct;
import com.doone.telmarket.domain.ServiceProductType;
import com.doone.telmarket.domain.ServiceState;
import com.doone.telmarket.domain.factory.ServiceFactory;
import com.doone.telmarket.domain.factory.ServicePageFactory;
import com.doone.telmarket.domain.ibator.ServiceClassify;
import com.doone.telmarket.domain.ibator.ServiceType;
import com.doone.telmarket.service.ImageChecker;
import com.doone.telmarket.service.ServiceClassifyOperation;
import com.doone.telmarket.service.ServiceOperation;
import com.doone.telmarket.service.ServiceProductOperation;
import com.doone.telmarket.service.ServiceTypeOperation;
import com.doone.telmarket.service.SiteResourceManager;
import com.opensymphony.xwork2.ActionContext;

/**
 * @package com.doone.telmarket.admin.action
 * @author 甘雨波
 * @date 2009-09-15 15:43
 * @description 增值业务配置ACTION
 *
 */
@Service("serviceAction")
public class ServiceAction extends BaseActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	Logger log = Logger.getLogger(ServiceAction.class);

	/****/

	private File uploadFile;

	private String titleTemp;

	private String uploadFileName;

	private String uploadFileContentType;

	private String serviceSummaryContent;

	private String page;

	private String serviceId;

	private String serviceName;

	private String serviceType;

	private String serviceClassify;

	private String value;

	private String serviceDesc;

	private String serviceCodeGrade;

	private String errorMessage;

	private String spName;

	private String serviceCode;

	private String serviceCodeType;

	private String serviceContent;

	private ServicePage servicePage;

	private String saveType;

	private String descriptionName;

	private String descriptionValue;

	private String descriptionId;

	private String orderMode;

	private String redirectUrl;

	private String canAccept;

	public String getCanAccept() {
		return canAccept;
	}

	public void setCanAccept(String canAccept) {
		this.canAccept = canAccept;
	}

	public String getTitleTemp() {
		return titleTemp;
	}

	public void setTitleTemp(String titleTemp) {
		this.titleTemp = titleTemp;
	}

	@Autowired
	private ServiceProductOperation remoteServiceProductOperation;

	private List<com.doone.telmarket.domain.Service> serviceList;

	@Autowired
	private ServiceOperation remoteServiceOperation;

	@Autowired
	private ImageChecker imageChecker;

	@Autowired
	private ServiceFactory serviceFactory;

	@Autowired
	private ServicePageFactory servicePageFactory;

	@Autowired
	private SiteResourceManager siteResourceManager;

	@Autowired
	private ServiceTypeOperation serviceTypeOperation;

	@Autowired
	private ServiceClassifyOperation serviceClassifyOperation;

	private String productName;

	private String productSummary;

	private String productType;

	private String productId;

	private String addServiceDescType;

	private String deleteServiceSescType;

	/**修改增值业务的图片及FLASH的分类**/
	private String updateType;

	/**
	 * @package org.springframework.stereotype.Service
	 * @author 甘雨波
	 * @description 新增增值业务
	 * @date 2009-09-16 12:05
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "saveService", interceptorRefs = { @InterceptorRef("fileUploadStack") }, results = {
			@Result(name = "success", location = "/admin/service/product.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String saveService() {
		try {

			ServiceType type = serviceTypeOperation.selectByPrimarykey(Integer.parseInt(serviceType));
			ServiceClassify classify = serviceClassifyOperation.selectByPrimaryKey(Integer.parseInt(serviceClassify));

			com.doone.telmarket.domain.Service service = serviceFactory.createService(serviceName, spName,
					ServiceState.E.toString(), type, classify);
			ServicePage servicePage = null;
			servicePage = servicePageFactory.createServcePage(service, Integer.parseInt(serviceCodeGrade),
					"tempSmall.jpg", "tempLogo.jpg", "tempFlash.swf", serviceSummaryContent,
					(List<ServicePageContent>) session.get("descMap"), orderMode, redirectUrl);

			File[] file = new File[3];
			Map<String, byte[]> fileMap = null;

			if (session.get("fileMap") != null) {
				fileMap = (Map) session.get("fileMap");
			} else {
				fileMap = new HashMap<String, byte[]>();
			}

			InputStream is = null;
			OutputStream os = null;
			try {
				ServletContext sc = (ServletContext) ActionContext.getContext().get(StrutsStatics.SERVLET_CONTEXT);

				if (fileMap.get("smallImage") != null) {
					String path = sc.getRealPath("/upload");
					is = new ByteArrayInputStream(fileMap.get("smallImage"));
					os = new FileOutputStream(path + "/tempSmall.jpg");
					byte[] b = new byte[1024];
					while (is.read(b) != -1) {
						os.write(b);
					}
					file[0] = new File(path + "/tempSmall.jpg");
				} else {
					String path = sc.getRealPath("/images");
					file[0] = new File(path + "/emptySmall.jpg");
				}

				//log.info("file[0]:"+file[0]);

				if (fileMap.get("logoImage") != null) {
					String path = sc.getRealPath("/upload");
					is = new ByteArrayInputStream(fileMap.get("logoImage"));
					os = new FileOutputStream(path + "/tempLogo.jpg");
					byte[] b = new byte[1024];
					while (is.read(b) != -1) {
						os.write(b);
					}
					file[1] = new File(path + "/tempLogo.jpg");
				} else {
					String path = sc.getRealPath("/images");
					file[1] = new File(path + "/emptyLogo.jpg");
				}

				//log.info("file[1]:"+file[1]);
				if (fileMap.get("flash") != null) {
					String path = sc.getRealPath("/upload");
					is = new ByteArrayInputStream(fileMap.get("flash"));
					os = new FileOutputStream(path + "/tempFlash.swf");
					byte[] b = new byte[1024];
					while (is.read(b) != -1) {
						os.write(b);
					}
					file[2] = new File(path + "/tempFlash.swf");
				} else {
					String path = sc.getRealPath("/flash");
					file[2] = new File(path + "/emptyFlash.swf");
					servicePage.setPageFlashPath("//flash//emptyFlash.swf");
				}
				//log.info("file[2]:"+file[2]);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (os != null) {
					os.close();
				}
				if (is != null) {
					os.close();
				}
			}

			//使用默认的图片及FLASH,不验证图片
			if (session.get("fileMap") != null) {
				String str = imageChecker.checkImage(file);
				if (str.equals("F")) {
					errorMessage = "系统繁忙，请稍后再试";
					return "error";
				}
				if (!str.equals("S")) {
					errorMessage = str;
					return "error";
				}
			}
			session.remove("fileMap");

			//log.info("type"+type.getServiceTypeName());
			//log.info("classify"+classify.getServiceClassifyName());

			session.put("descMap", null);/*使用完后清空*/

			String[] fileNames = new String[3];
			fileNames[0] = servicePage.getPageSmallIconPath();
			fileNames[1] = servicePage.getPageLogoPath();
			fileNames[2] = servicePage.getPageFlashPath();

			siteResourceManager.uploadFiles(file, fileNames);
			//log.info("。。。。。。。。。。。。。。。传文件成功");

			if (servicePage != null) {
				session.put("servicePage", servicePage);
				page = "service.jsp";
				return "success";
			} else {
				errorMessage = "处理页面数据失败";
				return "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
			errorMessage = "系统繁忙，请稍候再试";
			return "error";
		}

	}

	/**
	 * @package org.springframework.stereotype.Service
	 * @author 甘雨波
	 * @description 保存新增增值业务的操作数据及生成静态页面
	 * @date 2009-09-18 14:49
	 * @return
	 */
	@Action(value = "saveOpration")
	public void saveOpration() {
		try {
			servicePage = (ServicePage) session.get("servicePage");
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					org.apache.struts2.StrutsStatics.HTTP_REQUEST);
			HttpSession session = request.getSession();
			ServletContext sc = (ServletContext) ActionContext.getContext().get(StrutsStatics.SERVLET_CONTEXT);
			String path = sc.getRealPath("/");
			if ("update".equals(saveType)) {
				remoteServiceOperation.updateService(servicePage, session.getId(), path);
				generatePage(path, session.getId());
				page = "/admin/service/toOperationService.jsp";
			} else {
				servicePage.setContents(change(servicePage.getContents()));
				remoteServiceOperation.saveService(servicePage, session.getId(), path);
				List<ServicePageContent> spc =  servicePage.getContents();
			
				for(int i=0;i<spc.size();i++){
					System.out.println("WEB:::::t::::::"+spc.get(i).getTitle());
					System.out.println("WEB::::::c:::::"+spc.get(i).getContent());
				}
				generatePage(path, session.getId());
				page = "/admin/service/service.jsp";
			}
			responseWrite("生成页面成功");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("生成页面失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	private void generatePage(String rootPath, String sessionId) {
		ActionContext ac = ActionContext.getContext();
		HttpServletRequest sr = (HttpServletRequest) ac.get(StrutsStatics.HTTP_REQUEST);
		StringBuffer pagePath = new StringBuffer();
		pagePath.append("http://");
		pagePath.append(sr.getLocalAddr());
		pagePath.append(":");
		pagePath.append(sr.getLocalPort());
		pagePath.append("/");
		pagePath.append(sr.getContextPath());
		pagePath.append("/admin/serviceTemplet.jsp;jsessionid=" + sessionId);
		servicePage.setPageUrl("/web/service/" + servicePage.getService().getServiceCode() + ".html");
		try {
			siteResourceManager.generatePage(rootPath, pagePath.toString(), servicePage.getPageUrl());
			//页面生成以后把SESSION里的SERVICEPAGE清空
			session.put("servicePage", null);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("生成静态页面失败");
		}

	}

	/**
	 * 
	 * @author 甘雨波
	 * @description  根据类型取得SERVICE
	 * @date 2009-9-21
	 */
	@Action(value = "getServiceByType", results = {
			@Result(name = "success", location = "/admin/service/toOperationService.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String getServiceByType() {
		try {
			serviceList = remoteServiceOperation.selectServiceByType(serviceType, serviceClassify);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}

	/**
	 * 
	 * @author 甘雨波
	 * @description  根据SERVICEID取得SERVICE
	 * @date 2009-9-21
	 */
	@SuppressWarnings("static-access")
	@Action(value = "selectServiceById")
	public void getServiceById() {
		try {
			com.doone.telmarket.domain.Service service = remoteServiceOperation.selectServiceById(serviceId);
			JSONUtil ju = new JSONUtil();
			//			Currency c = new Currency();
			//			c.setMoney(service.getServiceCost().getMoney().divide(new BigDecimal(100)));
			//			service.setServiceCost(c);
			String jsonString = ju.serialize(service);
			responseWrite(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @author 甘雨波
	 * @description  根据SERVICEID取得SERVICEPAGE
	 * @date 2009-9-21
	 */
	@Action(value = "selectServicePageByServiceId", results = {
			@Result(name = "success", location = "/admin/service/modifyService.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String selectServicePageByServiceId() {

		try {
			session.put("servicePage", null);
			//JSONUtil ju = new JSONUtil();

			//log.info("根据SERVICEID取得SERVICEPAGE   serviceId"+serviceId);

			ServicePage sp = remoteServiceOperation.selectServicePageByServiceId(serviceId);
			//String jsonString = ju.serialize(sp);
			//log.info("ju.serialize(sp):"+jsonString);
			//	responseWrite(jsonString);
			session.put("servicePage", sp);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";

		}
	}

	@Action(value = "deleteById")
	public void deleteService() {
		try {
			int count = remoteServiceOperation.deleteServiceById(serviceId);
			if (count != 0) {
				try{
					ServletContext sc = (ServletContext) ActionContext.getContext().get(StrutsStatics.SERVLET_CONTEXT);
					String path = sc.getRealPath("/web/service");
					path = path+"/"+serviceId+".html";
					File file = new File(path);
					if(file!=null){
						file.delete();
					}
					path = sc.getRealPath("/images/service");
					path = path+"/logo_"+serviceId+".jpg";
					file = new File(path);
					if(file!=null){
						file.delete();
					}
					path = sc.getRealPath("/images/service");
					path = path+"/small_icon_"+serviceId+".jpg";
					file = new File(path);
					if(file!=null){
						file.delete();
					}
				}catch (Exception e) {
					log.info("删除资源文件时失败：SERVICE_ID="+serviceId);
				}
				responseWrite("E");
			} else {
				responseWrite("F");
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("F");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	/**
	 * @package
	 * @author 甘雨波
	 * @description 保存增值业务的说明
	 * @date 2009-10-12
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "saveServiceDesc")
	public void saveServiceDesc() {
		//log.info("保存增值业务的说明");
		try {

			if ("add".equals(addServiceDescType)) {
				ServicePageContent spc = new ServicePageContent();
				spc.setContent(descriptionValue);
				spc.setTitle(descriptionName);
				List list = (ArrayList<String>) session.get("descMap");
				if (list == null) {
					list = new ArrayList<String>();
				}
				//log.info(descriptionValue);
				list.add(spc);
				session.put("descMap", list);

			} else {
				ServicePage sp = ((ServicePage) session.get("servicePage"));
				List<ServicePageContent> content = sp.getContents();
				ServicePageContent s = new ServicePageContent();
				s.setServicePage(sp);
				s.setTitle(descriptionName);
				s.setContent(descriptionValue);
				s.setServicePage(sp);
				content.add(s);
				sp.setContents(content);
				session.put("servicePage", sp);

				//log.info("descriptionValue"+descriptionValue);
			}
			responseWrite("保存描述信息成功");
			//log.warn("增值业务描述信息(标题："+descriptionName+")内容("+descriptionValue+")");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("保存描述信息失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	/**
	 * @package
	 * @author 甘雨波
	 * @description 删除增值业务的说明(删除内存中)
	 * @date 2009-10-13
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "delServiceDesc")
	public void delServiceDesc() {
		try {
			if ("add".equals(deleteServiceSescType)) {
				if (session.get("descMap") != null) {
					List<ServicePageContent> map = (List<ServicePageContent>) session.get("descMap");
					for (int i = 0; i < map.size(); i++) {
						if (descriptionName.equals(map.get(i).getTitle())) {
							map.remove(i);
							break;
						}
					}

				}
			} else {

				ServicePage spage = ((ServicePage) session.get("servicePage"));
				List<ServicePageContent> content = spage.getContents();
				for (int i = 0; i < content.size(); i++) {

					//log.info(content.get(i).getTitle()+"::::"+descriptionName);
					if (content.get(i).getTitle().equals(descriptionName)) {
						content.remove(i);
					}
				}

				//log.info("进入删除增值业务描述信息CONTENT个数:"+content.size());
				spage.setContents(content);
				session.put("servicePage", spage);
			}
			responseWrite("删除增值业务描述信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("删除增值业务描述信息失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * @package
	 * @author 甘雨波
	 * @description　保存缩略图
	 * @date 2009-10-12
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "saveSmallImage", interceptorRefs = { @InterceptorRef("fileUploadStack") })
	public void saveSmallImage() {
		try {
			Map<String, byte[]> fileMap = (Map) session.get("fileMap");
			if (fileMap == null) {
				fileMap = new HashMap<String, byte[]>();
			}

			fileMap.put("smallImage", fileToByteArray(uploadFile));

			session.put("fileMap", fileMap);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @package
	 * @author 甘雨波
	 * @description　保存LOGO图
	 * @date 2009-10-12
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "saveLogoImage", interceptorRefs = { @InterceptorRef("fileUploadStack") })
	public void saveLogoImage() {
		try {
			Map<String, byte[]> fileMap = (Map) session.get("fileMap");
			if (fileMap == null) {
				fileMap = new HashMap<String, byte[]>();
			}
			fileMap.put("logoImage", fileToByteArray(uploadFile));
			session.put("fileMap", fileMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @package
	 * @author 甘雨波
	 * @description　保存FLASH
	 * @date 2009-10-12
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "saveFlash", interceptorRefs = { @InterceptorRef("fileUploadStack") })
	public void saveFlash() {
		try {
			Map<String, byte[]> fileMap = (Map) session.get("fileMap");
			if (fileMap == null) {
				fileMap = new HashMap<String, byte[]>();
			}
			fileMap.put("flash", fileToByteArray(uploadFile));
			session.put("fileMap", fileMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] fileToByteArray(File file) {
		ByteArrayOutputStream bStrm = null;
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			int ch;
			bStrm = new ByteArrayOutputStream();
			while ((ch = is.read()) != -1) {
				bStrm.write(ch);
			}
			return bStrm.toByteArray();
		} catch (Exception e) {
			return null;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception ee) {
				}
			}
			if (bStrm != null) {
				try {
					bStrm.close();
				} catch (Exception ee) {
				}
			}
		}
	}

	/**
	 * @package
	 * @author 甘雨波
	 * @description 保存产品类型
	 * @date 2009-10-12
	 */
	@Action(value = "saveProduct")
	public void saveProduct() {
		try {
			ServiceProduct sp = new ServiceProduct();
			if (session.get("servicePage") != null) {
				com.doone.telmarket.domain.Service service = ((ServicePage) session.get("servicePage")).getService();
				sp.setProductName(productName);
				Currency c = new Currency();
				c.setMoney(new BigDecimal(value).multiply(new BigDecimal(100)));
				sp.setProductCost(c);
				sp.setProductSummary(productSummary);
				sp.setProductId(productId);
				sp.setCanAccept(canAccept);
				log.info("canAccept====" + canAccept);
				sp.setService(service);
				if ("P".equals(productType)) {
					sp.setProductType(ServiceProductType.P);
				} else {
					sp.setProductType(ServiceProductType.C);
				}
				service.getProducts().add(sp);

				//log.info("保存产品类型,产品个数:"+service.getProducts().size());
				responseWrite("增加产品类别成功");
			} else {
				responseWrite("登陆超时");
			}

		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("增加产品类别失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	/**
	 * @package
	 * @author 甘雨波
	 * @description 删除产品类别
	 * @date 2009-10-13
	 */
	@Action(value = "deleteProduct")
	public void deleteProduct() {
		try {
			ServicePage servicePage = (ServicePage) session.get("servicePage");
			com.doone.telmarket.domain.Service service = servicePage.getService();
			List<ServiceProduct> li = service.getProducts();
			for (int i = 0; i < li.size(); i++) {
				if (productId.equals(li.get(i).getProductId())) {
					li.remove(i);
				}
			}
			//log.info("删除增值业务产品类别LIST个数:"+li.size());
			service.setProducts(li);
			servicePage.setService(service);
			session.put("servicePage", servicePage);
			responseWrite("删除增值业务产品类别成功");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("删除增值业务产品类别失败");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	/**
	 * @package
	 * @author 甘雨波
	 * @description 取消配置增值业务，以清空SESSION中的SERVICEPAGE
	 * @date 2009-10-13
	 */
	@Action(value = "cancelOprationService", results = {
			@Result(name = "success", location = "/admin/service/service.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String cancelOprationService() {
		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					org.apache.struts2.StrutsStatics.HTTP_REQUEST);
			HttpSession session = request.getSession();
			if (session.getAttribute("servicePage") != null) {
				session.setAttribute("servicePage", null);
				session.removeAttribute("fileMap");
				//log.info("取消配置增值业务，以清空SESSION中的SERVICEPAGE::::"+session.getAttribute("servicePage"));
			}
			//responseWrite("S");
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "success";
		}

	}

	@Action(value = "updateFile", interceptorRefs = { @InterceptorRef("fileUploadStack") })
	public void updateFile() {
		try {
			ServicePage sp = (ServicePage) session.get("servicePage");
			if ("small".equals(updateType)) {
				siteResourceManager.uploadFile(uploadFile, sp.getPageSmallIconPath());
			} else if ("logo".equals(updateType)) {
				siteResourceManager.uploadFile(uploadFile, sp.getPageLogoPath());
			} else {
				String flashFileName = "/flash/service/" + sp.getService().getServiceCode() + "_mod.swf";
				siteResourceManager.uploadFile(uploadFile, flashFileName);
				sp.setPageFlashPath(flashFileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Action(value = "updateService", results = { @Result(name = "success", location = "/admin/success.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String updateService() {
		try {
			ServicePage servicePage = (ServicePage) session.get("servicePage");
			com.doone.telmarket.domain.Service service = servicePage.getService();

			ServiceType type = serviceTypeOperation.selectByPrimarykey(Integer.parseInt(serviceType));
			ServiceClassify classify = serviceClassifyOperation.selectByPrimaryKey(Integer.parseInt(serviceClassify));

			service.setServiceClassify(classify);
			service.setServiceType(type);
			service.setServiceName(serviceName);
			service.setSpName(spName);
			servicePage.setRecommandGrade(Integer.parseInt(serviceCodeGrade));
			servicePage.setServiceSummaryContent(serviceSummaryContent);
			ServiceOrder order = new ServiceOrder();

			//	log.info(orderMode);

			if ("CRM".equals(orderMode)) {
				order.setServiceOrderMode(ServiceOrderMode.CRM);
			} else if ("ISM".equals(orderMode)) {
				order.setServiceOrderMode(ServiceOrderMode.ISM);
			} else if ("SSO".equals(orderMode)) {
				order.setServiceOrderMode(ServiceOrderMode.SSO);
			} else {
				order.setServiceOrderMode(ServiceOrderMode.RDT);
			}
			order.setRedirectUrl(redirectUrl);
			servicePage.setServiceOrder(order);
			servicePage.setService(service);
			session.put("servicePage", servicePage);
			page = "service/toOperationService.jsp";
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}

	}

	@Action("updateServicePageContent")
	public void updateServicePageContent() {

		try {
			ServicePage spg = (ServicePage) session.get("servicePage");
			ServicePageContent spc = new ServicePageContent();
			spc.setTitle(descriptionName);
			spc.setContent(descriptionValue);
			spc.setContentId(Integer.parseInt(descriptionId));
			
			remoteServiceOperation.updateServicePageContent(spc);
			List<ServicePageContent> contents = spg.getContents();
			for (int i = 0; i < contents.size(); i++) {
				if (Integer.parseInt(descriptionId)==contents.get(i).getContentId()) {
					contents.set(i, spc);
					spc.setServicePage(spg);
					spg.setContents(contents);
					break;
				}
			}

			session.put("servicePage", spg);
			responseWrite("更新成功");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("更新失败");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

	}

	@SuppressWarnings("static-access")
	@Action("getAllService")
	public void getAllProduct() {
		try {
			List<com.doone.telmarket.domain.Service> list = remoteServiceOperation.getAllService();
			JSONUtil json = new JSONUtil();
			responseWrite(json.serialize(list));
		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("获取数据失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getServiceId() {
		return serviceId;
	}

	public void setServiceId(String serviceId) {
		this.serviceId = serviceId;
	}

	public String getServiceName() {
		return serviceName;
	}

	public void setServiceName(String serviceName) {
		this.serviceName = serviceName;
	}

	public String getServiceType() {
		return serviceType;
	}

	public void setServiceType(String serviceType) {
		this.serviceType = serviceType;
	}

	public String getServiceClassify() {
		return serviceClassify;
	}

	public void setServiceClassify(String serviceClassify) {
		this.serviceClassify = serviceClassify;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getServiceDesc() {
		return serviceDesc;
	}

	public void setServiceDesc(String serviceDesc) {
		this.serviceDesc = serviceDesc;
	}

	public String getServiceCodeGrade() {
		return serviceCodeGrade;
	}

	public void setServiceCodeGrade(String serviceCodeGrade) {
		this.serviceCodeGrade = serviceCodeGrade;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public String getSpName() {
		return spName;
	}

	public void setSpName(String spName) {
		this.spName = spName;
	}

	public String getServiceCodeType() {
		return serviceCodeType;
	}

	public void setServiceCodeType(String serviceCodeType) {
		this.serviceCodeType = serviceCodeType;
	}

	public String getServiceContent() {
		return serviceContent;
	}

	public void setServiceContent(String serviceContent) {
		this.serviceContent = serviceContent;
	}

	public ServicePage getServicePage() {
		return servicePage;
	}

	public void setServicePage(ServicePage servicePage) {
		this.servicePage = servicePage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public List<com.doone.telmarket.domain.Service> getServiceList() {
		return serviceList;
	}

	public void setServiceList(List<com.doone.telmarket.domain.Service> serviceList) {
		this.serviceList = serviceList;
	}

	public String getSaveType() {
		return saveType;
	}

	public void setSaveType(String saveType) {
		this.saveType = saveType;
	}

	public String getDescriptionName() {
		return descriptionName;
	}

	public void setDescriptionName(String descriptionName) {
		this.descriptionName = descriptionName;
	}

	public String getDescriptionValue() {
		return descriptionValue;
	}

	public void setDescriptionValue(String descriptionValue) {
		this.descriptionValue = descriptionValue;
	}

	public String getServiceCode() {
		return serviceCode;
	}

	public void setServiceCode(String serviceCode) {
		this.serviceCode = serviceCode;
	}

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadFileContentType() {
		return uploadFileContentType;
	}

	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getProductSummary() {
		return productSummary;
	}

	public void setProductSummary(String productSummary) {
		this.productSummary = productSummary;
	}

	public String getProductType() {
		return productType;
	}

	public void setProductType(String productType) {
		this.productType = productType;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public String getOrderMode() {
		return orderMode;
	}

	public void setOrderMode(String orderMode) {
		this.orderMode = orderMode;
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}

	public String getAddServiceDescType() {
		return addServiceDescType;
	}

	public void setAddServiceDescType(String addServiceDescType) {
		this.addServiceDescType = addServiceDescType;
	}

	public String getDeleteServiceSescType() {
		return deleteServiceSescType;
	}

	public void setDeleteServiceSescType(String deleteServiceSescType) {
		this.deleteServiceSescType = deleteServiceSescType;
	}

	public String getUpdateType() {
		return updateType;
	}

	public void setUpdateType(String updateType) {
		this.updateType = updateType;
	}

	public String getServiceSummaryContent() {
		return serviceSummaryContent;
	}

	public void setServiceSummaryContent(String serviceSummaryContent) {
		this.serviceSummaryContent = serviceSummaryContent;
	}

	public String getDescriptionId() {
		return descriptionId;
	}

	public void setDescriptionId(String descriptionId) {
		this.descriptionId = descriptionId;
	}

	@Action(value = "updateProduct")
	public void updateProduct() {
		try {
			ServiceProduct sp = new ServiceProduct();
			ServicePage spg = (ServicePage) session.get("servicePage");
			sp.setProductName(productName);
			Currency c = new Currency();
			c.setMoney(new BigDecimal(value).multiply(new BigDecimal(100)));
			sp.setProductCost(c);
			sp.setProductSummary(productSummary);
			sp.setProductId(productId);
			sp.setCanAccept(canAccept);

			log.info("canAccept      " + canAccept);

			if ("P".equals(productType)) {
				sp.setProductType(ServiceProductType.P);
			} else {
				sp.setProductType(ServiceProductType.C);
			}
			remoteServiceProductOperation.updateServiceProduct(sp);

			List<ServiceProduct> products = spg.getService().getProducts();
			for (int i = 0; i < products.size(); i++) {
				ServiceProduct spd = (ServiceProduct) products.get(i);
				if (productId.equals(spd.getProductId())) {
					products.remove(i);
					sp.setService(spg.getService());
					products.add(sp);
					break;
				}
			}
			spg.getService().setProducts(products);
			session.put("servicePage", spg);

			responseWrite("更新成功");

		} catch (Exception e) {
			e.printStackTrace();
			try {
				responseWrite("更新失败");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}

	@Action(value = "queryServiceByServiceCodeAndServiceName", results = {
			@Result(name = "success", location = "/admin/service/toOperationService.jsp"),
			@Result(name = "error", location = "/admin/error.jsp") })
	public String queryService() {
		try {
			log.info("serviceCode= " + serviceCode);
			log.info("spName= " + spName);
			log.info("serviceName= " + serviceName);
			com.doone.telmarket.domain.Service service = new com.doone.telmarket.domain.Service();
			if (serviceCode == null || "".equals(serviceCode)) {
				service.setServiceCode(null);
			} else {
				service.setServiceCode(Integer.parseInt(serviceCode));
			}

			service.setSpName(spName);
			service.setServiceName(serviceName);

			serviceList = remoteServiceOperation.getServiceByServiceCodeAndServiceName(service);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}
	
	public List<ServicePageContent> change(List<ServicePageContent> li){
		List<ServicePageContent> li2 = new ArrayList<ServicePageContent>();
		for(int i=(li.size()-1);i>-1;i--){
			li2.add(li.get(i));
		}
		return li2;
	}

}
